//
//  FavoriteMigration.swift
//  hello
//
//  Created by 赵康 on 2024/11/11.
//

import Fluent

extension Favorite {
	struct Migration: AsyncMigration {
		var name: String { "FavoriteMigration" }
		
		func prepare(on database: any Database) async throws {
			try await database.schema(Favorite.schema)
				.id()
				.field(Favorite.FieldKeys.album, .uuid, .references(Album.schema, .id))
				.field(Favorite.FieldKeys.user, .uuid, .references(User.schema, .id))
				
				.field(Favorite.FieldKeys.createdAt, .datetime, .required)
				.field(Favorite.FieldKeys.updatedAt, .datetime, .required)
				.field(Favorite.FieldKeys.isDeleted, .bool, .required, .custom("DEFAULT FALSE"))
				.create()
		}
		func revert(on database: any Database) async throws {
			try await database.schema(Favorite.schema).delete()
		}
	}
}

// 添加文件夹外键的迁移
extension Favorite {
	struct AddFolderFieldMigration: AsyncMigration {
		var name: String { "AddFolderFieldToFavoriteMigration" }
		
		func prepare(on database: any Database) async throws {
			try await database.schema(Favorite.schema)
				.field(Favorite.FieldKeys.folder, .uuid, .references(Folder.schema, .id))
				.update()
		}
		
		func revert(on database: any Database) async throws {
			try await database.schema(Favorite.schema)
				.deleteField(Favorite.FieldKeys.folder)
				.update()
		}
	}
}

// 添加position字段的迁移
extension Favorite {
	struct AddPositionFieldMigration: AsyncMigration {
		var name: String { "AddPositionFieldToFavoriteMigration" }
		
		func prepare(on database: any Database) async throws {
			try await database.schema(Favorite.schema)
				.field(Favorite.FieldKeys.position, .int, .required, .custom("DEFAULT 0"))
				.update()
		}
		
		func revert(on database: any Database) async throws {
			try await database.schema(Favorite.schema)
				.deleteField(Favorite.FieldKeys.position)
				.update()
		}
	}
}
